#include "Triangle.hpp"
#include "rasterizer.hpp"
#include <Eigen/Eigen>
#include <iostream>
#include <opencv2/opencv.hpp>

constexpr double MY_PI = 3.1415926;

Eigen::Matrix4f get_view_matrix(Eigen::Vector3f eye_pos)
{
    Eigen::Matrix4f view = Eigen::Matrix4f::Identity();

    Eigen::Matrix4f translate;
    translate << 1, 0, 0, -eye_pos[0],
            0, 1, 0, -eye_pos[1],
            0, 0, 1, -eye_pos[2],
            0, 0, 0, 1;

    view = translate * view;

    return view;
}

Eigen::Matrix4f get_rotation(const Eigen::Vector3f& axis, float angle_degrees) {
    float angle_rad = angle_degrees * MY_PI / 180.0f;
    Eigen::Vector3f n = axis.normalized();  // 确保轴是单位向量
    Eigen::Matrix3f N;
    N << 0, -n.z(), n.y(),
         n.z(), 0, -n.x(),
        -n.y(), n.x(), 0;

    // 罗德里格斯旋转公式
    Eigen::Matrix3f R = Eigen::Matrix3f::Identity() * cos(angle_rad)
                      + (1 - cos(angle_rad)) * n * n.transpose()
                      + sin(angle_rad) * N;

    // 将 3x3 旋转矩阵嵌入 4x4 齐次矩阵
    Eigen::Matrix4f result = Eigen::Matrix4f::Identity();
    result.block<3, 3>(0, 0) = R;  // 直接赋值左上角 3x3 块

    return result;
}

Eigen::Matrix4f get_model_matrix(float rotation_angle)
{
    Eigen::Matrix4f model = Eigen::Matrix4f::Identity();

    double rotation_rad = rotation_angle * MY_PI / 180;
    float cos_alpha = cos(rotation_rad);
    float sin_alpha = sin(rotation_rad);
    model << cos_alpha, -sin_alpha, 0, 0,
            sin_alpha, cos_alpha, 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1;

    // 计算任意轴的旋转
    // model = get_rotation(Vector3f(1, 0, 0), 30) * model;
    model = get_rotation(Vector3f(0, 1, 0), 30) * model;

    return model;
}

Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio,
                                      float zNear, float zFar)
{
    Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();

    float cot_fov_2 = 1.0f / tan(eye_fov * MY_PI / 180 / 2);

    projection << -cot_fov_2 / aspect_ratio, 0, 0, 0,
            0, -cot_fov_2, 0, 0,
            0, 0, (zNear + zFar) / (zNear - zFar), -2 * zNear * zFar / (zNear - zFar),
            0, 0, 1, 0;

    return projection;
}

int main(int argc, const char **argv) {
    float angle = 0;
    bool command_line = false;
    std::string filename = "output.png";

    if (argc >= 3) {
        command_line = true;
        angle = std::stof(argv[2]); // -r by default
        if (argc == 4) {
            filename = std::string(argv[3]);
        } else
            return 0;
    }

    rst::rasterizer r(700, 700);

    Eigen::Vector3f eye_pos = {0, 0, 5};

    std::vector<Eigen::Vector3f> pos{{2, 0, -2}, {0, 2, -2}, {-2, 0, -2}};

    std::vector<Eigen::Vector3i> ind{{0, 1, 2}};

    auto pos_id = r.load_positions(pos);
    auto ind_id = r.load_indices(ind);

    int key = 0;
    int frame_count = 0;

    if (command_line) {
        r.clear(rst::Buffers::Color | rst::Buffers::Depth);

        r.set_model(get_model_matrix(angle));
        r.set_view(get_view_matrix(eye_pos));
        r.set_projection(get_projection_matrix(45, 1, 0.1, 50));

        r.draw(pos_id, ind_id, rst::Primitive::Triangle);

        cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
        image.convertTo(image, CV_8UC3, 1.0f);
        cv::imwrite(filename, image);

        return 0;
    }

    while (key != 27) {
        r.clear(rst::Buffers::Color | rst::Buffers::Depth);

        r.set_model(get_model_matrix(angle));
        r.set_view(get_view_matrix(eye_pos));
        r.set_projection(get_projection_matrix(45, 1, 0.1, 50));

        r.draw(pos_id, ind_id, rst::Primitive::Triangle);

        cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
        image.convertTo(image, CV_8UC3, 1.0f);
        cv::imshow("image", image);
        key = cv::waitKey(10);

        std::cout << "frame count: " << frame_count++ << '\n';

        if (key == 'a') {
            angle += 10;
        } else if (key == 'd') {
            angle -= 10;
        }
    }

    return 0;
}
